﻿using System;
using System.Text;

namespace IceDog.DNC.Library.Standard.Permisssion.Yellow
{
    /// <summary>
    /// 通过每一位定义一种权限来计算，位为0表示无权限，1表示有权限
    /// </summary>
    public class PermissionItem : IPermissionAction<PermissionType>
    {
        public int Permission { get; set; }
        public int AddPermission(PermissionType permission)
        {
            var pos = (int)permission;
            if (HasPermission(permission))
            {
                return (this.Permission >> pos) & 1;
            }
            this.Permission = this.Permission + (1 << pos);//将第pos位设置为1
            return this.Permission;
        }

        public int RemovePermission(PermissionType permission)
        {
            var pos = (int)permission;
            if (!HasPermission(permission))
            {
                return (this.Permission >> pos) & 1;
            }
            this.Permission = this.Permission + (1 >> pos);//将第pos位设置为0
            return this.Permission;
        }

        public bool HasPermission(PermissionType permission)
        {
            var pos = (int)permission;
            var perm = this.Permission >> pos;
            return (perm & 1) == 1;
        }

        /// <summary>
        /// 获取二进制字符串
        /// </summary>
        /// <returns></returns>
        public string GetBinaryString()
        {
            var perm = this.Permission;
            byte[] perms = new byte[32];
            int pos = 32;
            do
            {
                perms[--pos] = (byte)(perm & 1);
                perm = perm >> 1;//右移一位，相当除以2  
            } while (perm != 0);
            var sb = new StringBuilder(32);
            for (int i = 0; i < perms.Length; i++)
            {
                sb.Append(perms[i]);
            }
            return sb.ToString();
        }
    }
}
